<template>
    <view>	
		<u-row customStyle="margin-bottom: 10px" style="margin-top: 15px;">
			<u-col span="3">
				<view style=" font-size: 15px; font-weight: bold;  display: flex; justify-content: center;">设备号:</view>
				<view class="englishInfo">DeviceNumber</view>
			</u-col>
			<u-col span="6">
				<u--input placeholder="请输入设备号" border="surround" v-model="deviceNumber2"  type="text" clearable></u--input>
			</u-col>
			<u-col span="3">
				<button @click="sweep" class="sweep-bt">
					<image src="https://cdnjson.com/images/2023/09/26/987a9d501811c03b63684197591990d2.png" style="width: 20px; height: 20px;"></image>
					<text style="font-size: 13px; padding-left: 3px; color: #ffffff">扫一扫</text>
				</button>
			</u-col>
		</u-row>
		<u-row customStyle="margin-bottom: 10px">
			<u-col span="3">
				<view class="title" >姓名:</view>
				<view class="englishInfo">Name</view>
			</u-col>
			<u-col span="8">
				<u--input placeholder="请输入您的名字" border="surround" v-model="customername" type="text" clearable></u--input>
			</u-col>
		</u-row>
		<u-row customStyle="margin-bottom: 10px">
			<u-col span="3">
				<view class="title" >联系方式:</view>
				<view class="englishInfo">ContactWay</view>
			</u-col>
			<u-col span="8">
				<u--input placeholder="请输入手机号码" border="surround" v-model="customerphone" type="tel"
				maxlength='11'  clearable></u--input>
				<!-- @blur='phoneBlur' -->
			</u-col>
		</u-row>
		<!-- <u-gap height="5px" bgColor="#ffffff "></u-gap> -->
		<!--   工单上报位置  -->
		<u-row customStyle="margin-bottom: 10px">
			<u-col span="2.5">
				<view style="font-size: 15px; font-weight: bold; display: flex; justify-content: center;">上报位置:</view>
				<view class="englishInfo">location</view>
			</u-col>
			<u-col span="6">
				<u-read-more ref="uReadMore" showHeight="40" closeText = '显示完整地址'  :shadowStyle="shadowStyle">
					<u-parse :content="workLocation" @load="load"></u-parse>
				</u-read-more>
			</u-col>
			<u-col span="3.5">
				<button @click="locationBt" class="sweep-bt">
					<image src="../../static/location.png" style="width: 20px; height: 20px;"></image>
					<text style="font-size: 13px; padding-left: 3px; color: #ffffff;">重新定位</text>
				</button>
			</u-col>
		</u-row>
		<view class="tips">*请确保工单上报位置与设备位置距离不超过2000m,否则无法提交订单Ensure that the distance between the work order
		 reporting location and the device location does not exceed 2000m. Otherwise, the order cannot be submitted
		</view>
		<u-gap height="10px"></u-gap>
		<view>
			<view class="uni-form-item uni-column user-input">
				<text style="color: crimson; font-size: 20px;">*</text>
				<view style="font-size: 15px; font-weight: bold;">详情描述(Detail Description):</view>
			</view>
		<view class="textarea_box">
			<textarea class="textarea" placeholder="请填写10字以上的问题描述，以便我们更好的帮助您解决问题，提高产品质量。" placeholder-style="font-size:28rpx" maxlength="200" @input="descInput" v-model="desc" />
			<view class="num">{{desc.length}}/200</view>
		</view>	
		</view>
            <view class="img-box">
                <view class="img-box-top">
                    <!-- <text class="list-star">*</text> -->
					<u-row customStyle="margin-bottom: 10px">
						<u-col span="3">
							<view style="font-size: 32rpx; font-weight: bold;">上传图片:</view>
							<view class="englishInfo">UploadPictures</view>
						</u-col>
						<u-col span="9">
							<text class="img-txt">（建议图片大小不要超过2M且最多上传6张图片）</text>
						</u-col>
					</u-row>
                </view>
                <!-- 图片 -->
                <view class="imgs-list">
                    <view class="goods-box">
                        <view class="imgList" v-for="(item, key) in fileList" :key="key">
                            <image class="del" src="../../static/del.png" @click="delImage(key)"></image> 
                            <image class="imgList" :src="item" @click="previewImg(fileList,key)"></image>
                        </view>
                        <image class="imgList" src="../../static/shangchuan.png" @click="addImage"></image>
                    </view>
                </view>
				<u-divider ></u-divider>  <!-- 分隔线 -->
            </view>
			<button  class="submitBt" @click="workOrderSubmit" >提交(submit)</button>
			<u-gap height="80px"></u-gap>
			
			<userTab ></userTab>
      </view>
</template>
<script>
	import amap from '@/static/js/amap-wx.130.js';
	let deviceNumber;
	var _this;
	// import userTab from '@/pages/UserTabBar/userTab.vue' 
	let imgStr='';
	var imgSplice='';
 export default {
	 // components: {
	 //     'view-tabbar': userTab
	 // },
     data() {
            return {
				// imgSplice:'',
                imglist: [],
                fileList: [], // 存储图片的数组，
                urlStr: "", //  后端返回的图片数据拼接
				desc: '.',
				deviceNumber2: ''  ,//设备号
				customername: '',  //客户名字
				customerphone: '',  // 客户电话 
				openid: ''  ,
				gdKeys:'a65ca3f7e4c4cf0f17d64768ce74a85e',
				workLocation:'',  //地址
				workLng:'',       // 经度
				workLat:'',
				
				shadowStyle:{  // 去除 u-read-more 阴影
					backgroundImage: "none",
				}
            }
    },
 
	 methods:{
		 
		 locationBt(){   // 重新定位 
			const _this = this;
			this.amapPlugin = new amap.AMapWX({
			    key: this.gdKeys
			});
			
			uni.showLoading({
				title: '定位中.....'
			});
			_this.amapPlugin.getRegeo({
				success: (data) => {
					//
					_this.workLocation = data[0].regeocodeData.formatted_address;
					console.log('------定位数据 -------',_this.workLocation);
					_this.workLng = data[0].longitude;
					_this.workLat = data[0].latitude;
					uni.hideLoading();
				},
				fail: (err) => {
					console.log('---错误 ---',err) 
				},
				complete:(res) =>{
					console.log('*****complete------',res)
					uni.hideLoading();
				}
			});
		 },	 
		 load() {		//   查看更多 
		 	this.$refs.uReadMore.init();
		 },
		 sweep(){  // 扫一扫
			uni.showModal({
				title: "提示",
				content: "请先扫码获取设备号!",
				showCancel:true,
				success: (res) => {
					if (res.confirm) {
						_this = this
						uni.scanCode({  
							success: (res) => {
							let scanStr = res.result 
							if(scanStr.substring(0,4) == 'SMAC'){
								deviceNumber = res.result;
							_this.deviceNumber2 = deviceNumber
							console.log(_this.deviceNumber2)
							uni.showToast({
								title: '设备号：'+ deviceNumber,
								duration: 3000,
								icon: 'none'
							});
							}else{
								uni.showToast({
									title: '请扫正确的设备二维码',
									duration:2000,
									icon:'none'
								})
							}
							},
							fail: (res) => {
							  uni.showToast({
							  	title: '请扫正确的二维码！',
								duration:2000,
								icon: 'none'
							  }) 
							  // 处理扫码失败的情况 
							}
						})
					} else if (res.cancel) {
						_this.deviceNumber2 = ''
						// console.log('用户点击取消');
					}
				}
				
			})
			 
		 },
		phoneBlur(e){  // 手机号正则 
			// console.log("-----失去焦点-------",e)
			let reg = /^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\d{8}$/;
			if (!reg.test(e)) {
				uni.showToast({
					icon: 'none',
					title: '请输入正确的11位手机号'
				})
				this.customerphone = '';
				return false;
			}
		 },
		 
		 workOrderSubmit(){   // 工单提交
			this.openid = uni.getStorageSync('clientOpenid')
			for (let i = 0; i < this.fileList.length; i++) {
				let item =  this.fileList[i];
				let p =  this.requestMessage(item);  
				Promise.all([p]).then( results  => {
				        // console.log(results[0] ,"-------  results    ---------");
						imgSplice += results[0] +','
				    })
			}
			this.timerIntv = setTimeout( () => {
			    console.log(imgSplice,'------imgSplice -------')
				if(this.customername == '' || this.customerphone == '' || this.desc == '' || imgSplice ==''){
					uni.showToast({
						title: '上报信息不为空',
					
						icon: 'none'
					})
				}else{
					uni.request({
						url: 'https://www.smacaftersales.com:443/workOrder/workOrder/addWorkOrder',
						method: 'POST',
						data:{
							serialnumber: this.deviceNumber2,
							customername: this.customername,
							customerphone: this.customerphone,
							problemdescription: this.desc,
							detailspath: imgSplice,
							openId: this.openid,
							workLocation: this.workLocation,
							workLng: this.workLng,
							workLat: this.workLat
						},
						success: (res) => {
							console.log(res.data,'----  工单上报 --------')
							// imgSplice = null
							
							if(res.data.msg == '操作成功'){
								uni.showToast({
									title: 'success',
									duration:1000,
									icon: 'success'
								})
								this.timerIntv = setTimeout( () => {
									uni.switchTab({
									url: '/pages/clientVue/bindDevice'
									})
								}, 1100)
							}else{
								//  设备距离与 工单上报距离超过2000m
								uni.showModal({
									title: '提示(Tips)',
									content: res.data.msg,
									showCancel: false
								})
							}
							
						},
					})
				}	
	
			}, 1000)
		 },
		requestMessage(item) {  // 上传图片 
			return new Promise((resolve, reject) => {
				uni.uploadFile({ 
					url: 'https://www.smacaftersales.com:443/workOrder/workOrder/fileUpload', 
					filePath: item,
					name: 'file',
					header: {
						'content-type': 'multipart/form-data'
					},
					success: function(res) {
						imgStr = res.data
						resolve(imgStr)
					},
					fail: function(e) {
						uni.showToast({
							title: 'error',
							icon: 'loading',
							duration: 2000
						})
					},
			})
			})
		},
		  //  文本域  
		descInput(e) {
			console.log(e.detail.value.length, '输入的字数')
		},
		  // 新增图片 
		addImage() {
			console.log('点击添加图片---------')
			const max = 6; //上传图片数量
			const count = max - this.fileList.length
			uni.chooseImage({
				count: count, // 上传图片最多6个可以自己调
				success: (res) => {
					this.fileList = [...this.fileList, ...res.tempFilePaths]
				},
				fail: (res) => {
					console.log("无法获取图片了-------------------")
				}
			})
		},

		// 删除图片
		delImage(id) {
			this.fileList.splice(id, 1)
		},
		// 预览图片功能
		previewImg(urls, i) {
			// console.log(urls);
			uni.previewImage({
				urls, //所有要预览的图片的地址集合 必须数组形式 
				current: urls[i] //当前图片地址,点击预览哪个预览的哪个传的 i 是索引
			})
		},
	},
	onLoad() {  
		this.deviceNumber2 = ''
		this.customername=''
		this.customerphone = ''
		this.desc = ''
		this.fileList = []
		this.imglist = ''
		imgSplice=''
		console.log('****',imgSplice,'------imgSplice-------')
		const _this = this;
		this.amapPlugin = new amap.AMapWX({
		    key: this.gdKeys
		});
		//  获取定位信息
		uni.showLoading({
			title: '定位中.....'
		});
		_this.amapPlugin.getRegeo({
			success: (data) => {
				// console.table(data[0], '当前定位')
				_this.workLocation = data[0].regeocodeData.formatted_address;
				console.log('------定位数据 -------',_this.workLocation);
				_this.workLng = data[0].longitude;
				_this.workLat = data[0].latitude;
				uni.hideLoading({
				fial:(err)=>{}
				})
			},
			fail: (err) => {
				console.log('--- 定位错误了 ---',err)
				// uni.hideLoading();
			},
			complete: () => {
				// 隐藏loading
				uni.hideLoading();
			}
		});
	},
    }
 
</script>
<style>
	/* 页面背景 */
	page {
		background-color: #ffffff;
	}
</style>
<style scoped lang="scss">
	.englishInfo{
		display: flex;
		color: #74daff;
		align-items: center;//子控件垂直居中
		justify-content: center;//子控件水平居中
	}
	.title{
		// width: 90px;
		// height: 20px;
		font-size: 16px;
		font-weight: bold;
		display: flex; justify-content: center;
	} 
	.tips{
		width: 100%;
		height: 18px;
		// border: 3rpx solid #6699FF;
		font-size: 10px;
		color: #ff0000;
		text-align: center;
		margin-bottom: 10px ;
	}
	.sweep-bt{
		background-color: #00a9fd;
		border-radius: 15px;
		height: 35px;
		display: flex; 
		justify-content: center; //水平居中
		align-items: center;
	}
	.sweep-bt:after{
		border: none;
	}
	
	.user-input{
		width: 390px;
		margin: 15px 10px ;
		display: flex;
		.input{
			width: 200px;
			margin-left: 10px;
			// border: 1px solid #0f2d2d;
			// border-radius: 5px;
			// border-color: #000000;
		}
	}

    .goods-box {
        display: flex;
        flex-wrap: wrap;
 
        // 图片列表
        .imgList {
            position: relative;
            width: 100rpx;
            height: 100rpx;
            margin: 0 47rpx 30rpx 0;
        }
 
        // 删除图片
        .del {
            position: absolute;
            width: 35rpx;
            height: 35rpx;
            right: 5rpx;
            z-index: 999;
        }
    }
    /* 图片 */
    .img-box {
        padding: 34rpx 0 35rpx 23rpx;
        margin-top: 24rpx;
        background: #FFFFFF;
        border-radius: 10rpx;
    }
 
    .imgs {
        width: 10rpx;
        height: 10rpx;
    }
 
    .img-box-top {
        display: flex;
        font-size: 28rpx;
    }
 
    .img-txt {
        font-size: 24rpx;
        color: #959595;
        margin-left: 15rpx;
    }
 
    .imgs-list {
        display: flex;
        margin-top: 35rpx;
    }
 
    .showLoadImg {
        position: relative;
    }
 
    .upLoadImg-img {
        width: 122rpx;
        height: 122rpx;
    }
 
    .group image {
        width: 22rpx;
        height: 22rpx;
    }
 
    .q-image-remover {
        width: 20rpx;
        position: absolute;
        right: 0rpx;
        top: -15rpx;
        /* z-index: 99; */
    }
 
    .img-li {
        width: 122rpx;
        height: 122rpx;
        border: 2rpx dashed #959595;
        margin-left: 16rpx;
        border-radius: 10rpx;
    }
 
    .upLoadImg {
        width: 50rpx;
        height: 50rpx;
        margin: 30rpx 30rpx;
    }
	// 文本域 
	.textarea_box{
		margin: 5px;
		background-color: #ffffff;
		border: 3rpx solid #d9d9d9;
		border-radius: 6px;
		::v-deep .uni-textarea-textarea{
			font-size: 28rpx;
			line-height: 45rpx;
		}
		.num{
			text-align: right;
			color: gray
		}
	}
	.submitBt{
		width: 180px;
		height: 40px;
		display: flex;
		margin-top: 80px;
		justify-content: center;
		border-radius: 25px;
		border: 3rpx solid #6699FF;
		font-size: unset;
		
	}
 
</style>